const router = require('koa-router')();
const config = require('../config/index');
const jwt = require('jsonwebtoken');
const crypto = require('crypto');

const User = require('../models/user');

const { secret } = config;

router.get('/login', async (ctx, next) => {
    await ctx.render('login', {
        title: '登陆'
    })
});

router.post('/login', async (ctx, next) => {
    const result = {
        code: 0,
        msg: 'success'
    }
    const { username, password } = ctx.request.body;
    // 查询数据库中user表
    const user = await User.find({
        where: {
            username
        }
    });
    const md5 = crypto.createHash('md5');
    // 加密后的密码
    const cryptoPWD = md5.update(password).digest('hex');
    // 如果用户存在，密码正确 返回相应的token
    if (user && user.password === cryptoPWD) {
        const { id, username } = user;
        // 生成token
        const token = jwt.sign({
            id,
            user
        }, secret, {
            expiresIn: 60 * 60
        });
        // 返回token数据
        result.token = token;
    } else {
        result.code = 1;
        result.msg = '用户名或密码错误';
    }
    ctx.body = result;
});

module.exports = router;
